/*
 * @Author: silence
 * @Date: 2022-07-27 10:44:25
 * @LastEditors: silence silence9685@163.com
 * @LastEditTime: 2023-08-10 17:39:10
 * @Description: 
 */
import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:sil_utils_package/sil_utils_package.dart';

import 'DownFile.dart';

class FileImageUtil {
  /**
   * 下载图片，自带简易缓存
   */
  static Future<FileImageEntity?> downImage(String url) async {
    if (SilTools.stringIsEmpty(url)) return null;
    if (!url.startsWith("http")) return null;

    //路径准备
    var localPath = await DownFile.getPhoneLocalPath();
    localPath = "${localPath}/myimgs";
    String filePath = "${localPath}/${url.split("/").last}";

    Directory dir = Directory(localPath);
    if ((await dir.exists()) == false) {
      await dir.create();
    }

    //如果本地存在，不用下载
    File localFile = File(filePath);
    if ((await localFile.exists()) == true) {
      return await _createEntity(filePath, url);
    }

    //下载准备
    BaseOptions options =
        BaseOptions(connectTimeout: Duration(milliseconds: 6000), receiveTimeout: Duration(milliseconds: 10000));
    Dio dio = Dio(options);
    var response = await dio.download(url, filePath);

    if (response.statusCode == 200) {
      //下载成功

      //读取本地图片信息
      return await _createEntity(filePath, url);
    }

    return null;
  }

  /**
   * 返回实体类
   */
  static Future<FileImageEntity?> _createEntity(
      String filePath, String url) async {
    Completer<FileImageEntity> completer = new Completer<FileImageEntity>();

    Image image = Image.file(File(filePath));
    image.image
        .resolve(new ImageConfiguration())
        .addListener(new ImageStreamListener((ImageInfo info, bool value) {
      if (info != null && info.image != null) {
        FileImageEntity entity = FileImageEntity();
        entity.width = "${info.image.width}";
        entity.height = "${info.image.height}";
        entity.url = url;
        entity.filePath = filePath;
        completer.complete(entity);
      } else {
        completer.complete(null);
      }
    }));

    return completer.future;
  }
}

class FileImageEntity {
  String? width;
  String? height;
  String? url;
  String? filePath;

  FileImageEntity({this.width, this.height, this.url, this.filePath});
}
